package com.chang.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chang.common.constant.ProductConstant;
import com.chang.common.to.SkuEsModel;
import com.chang.common.to.SkuReductionTo;
import com.chang.common.to.SpuBoundTo;
import com.chang.common.utils.PageUtils;
import com.chang.common.utils.Query;
import com.chang.common.utils.R;
import com.chang.common.utils.Result;
import com.chang.common.vo.SkuStockVo;
import com.chang.product.entity.*;
import com.chang.product.feign.CouponFeignService;
import com.chang.product.feign.SearchFeignService;
import com.chang.product.feign.WareFeignService;
import com.chang.product.mapper.SpuInfoDao;
import com.chang.product.service.*;
import com.chang.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    private final SpuInfoDescService spuInfoDescService;
    private final SkuImagesService skuImagesService;
    private final SkuInfoService skuInfoService;
    private final SpuImagesService spuImagesService;
    private final AttrService attrService;
    private final ProductAttrValueService productAttrValueService;
    private final SkuSaleAttrValueService skuSaleAttrValueService;
    private final CouponFeignService couponFeignService;
    private final BrandService brandService;
    private final CategoryService categoryService;
    private final WareFeignService wareFeignService;
    private final SearchFeignService searchFeignService;

    // 构造注入
    public SpuInfoServiceImpl(SpuInfoDescService spuInfoDescService, SkuImagesService skuImagesService, SkuInfoService skuInfoService, SpuImagesService spuImagesService, AttrService attrService, ProductAttrValueService productAttrValueService, SkuSaleAttrValueService skuSaleAttrValueService, CouponFeignService couponFeignService, BrandService brandService, CategoryService categoryService, WareFeignService wareFeignService, SearchFeignService searchFeignService) {
        this.spuInfoDescService = spuInfoDescService;
        this.skuImagesService = skuImagesService;
        this.skuInfoService = skuInfoService;
        this.spuImagesService = spuImagesService;
        this.attrService = attrService;
        this.productAttrValueService = productAttrValueService;
        this.skuSaleAttrValueService = skuSaleAttrValueService;
        this.couponFeignService = couponFeignService;
        this.brandService = brandService;
        this.categoryService = categoryService;
        this.wareFeignService = wareFeignService;
        this.searchFeignService = searchFeignService;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }


    /*
     * @Author Chang
     * @Date 2024/3/20 17:07
     * @Description 商品信息分表保存
     * todo 更多细节在高级篇完善
     * @Param [spuSaveVo]
     * @Return void
     * @Since version 1.0
     */
    @Override
    @Transactional
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        // 保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity); // 插入时间和修改时间已经配置自动填充
        this.saveBaseSpuInfo(spuInfoEntity);

        // 后续分表的id都以已保存spu的id为准
        Long spuId = spuInfoEntity.getId();

        // 保存spu描述图片 pms_spu_info_desc
        List<String> decriptdecript = spuSaveVo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuId);
        // 这里直接将String的方法将集合中每个对象用','连接 将连接后的整个字符串直接填充到对象中
        spuInfoDescEntity.setDecript(String.join(",", decriptdecript));
        spuInfoDescService.save(spuInfoDescEntity);

        // 保存spu图片集 pms_spu_images
        List<String> images = spuSaveVo.getImages();
        spuImagesService.saveImages(spuId, images);

        // 保存spu规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(item -> {
            ProductAttrValueEntity attrValueEntity = new ProductAttrValueEntity();
            attrValueEntity.setAttrId(item.getAttrId());
            // 这里没有直接指明name字段，需要再查一下
            attrValueEntity.setAttrName(attrService.getById(item.getAttrId()).getAttrName());
            attrValueEntity.setSpuId(spuId);
            attrValueEntity.setAttrValue(item.getAttrValues());
            attrValueEntity.setQuickShow(item.getShowDesc());
            return attrValueEntity;
        }).toList();
        productAttrValueService.saveBatch(productAttrValueEntities);


        // 保存spu的积分信息 gulimall_sms
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuId);
        R r1 = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r1.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }

        // 保存当前spu对应的所有sku信息

        // 保存sku的基本信息 pms_sku_info
        List<Skus> skusList = spuSaveVo.getSkus();
        Long brandId = spuInfoEntity.getBrandId();
        Long catalogId = spuInfoEntity.getCatalogId();
        if (!skusList.isEmpty()) {
            skusList.forEach(sku -> {
                String defaultImg = "";

                for (Images img : sku.getImages()) {
                    if (img.getDefaultImg() == 1) {
                        defaultImg = img.getImgUrl();
                    }
                }

                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, skuInfoEntity);
                skuInfoEntity.setBrandId(brandId);
                skuInfoEntity.setCatalogId(catalogId);
                skuInfoEntity.setSpuId(spuId);
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.saveSkuInfo(skuInfoEntity);

                // sku基本信息保存完之后，后续的其他sku表格都要使用这个skuId
                Long skuId = skuInfoEntity.getSkuId();

                // 保存sku的图片信息 pms_sku_images  这里图片需要先关联sku的id
                // TODO 没有图片路径的无需保存
                List<SkuImagesEntity> imagesEntityList = sku.getImages().stream()
                        .filter(img ->
                                StringUtils.hasLength(img.getImgUrl()) // 图片url地址为空就不用保存了
                        ).map(img -> {
                            SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                            skuImagesEntity.setSkuId(skuId);
                            skuImagesEntity.setDefaultImg(img.getDefaultImg());
                            skuImagesEntity.setImgUrl(img.getImgUrl());
                            return skuImagesEntity;
                        }).toList();
                skuImagesService.saveBatch(imagesEntityList);

                // 保存sku的销售属性信息 pms_sku_sale_attr_value
                List<Attr> attr = sku.getAttr();
                List<SkuSaleAttrValueEntity> saleAttrValueEntities = attr.stream().map(attrs -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attrs, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).toList();
                skuSaleAttrValueService.saveBatch(saleAttrValueEntities);

                // 保存sku的优惠满减等信息  需要跨库 gulimall_sms sms_sku_ladder 满多少减多少 满几件打几折
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                // 前端传递过来 满多少件FullCount 和 满多少元FullPrice 这两个字段也需要进行校验
                // skuReductionTo.getFullPrice().compareTo(BigDecimal.ZERO) ==1 代表getFullPrice的值比0大
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(BigDecimal.ZERO) == 1) {
                    // 传递过来的如果是减0元 和 打0折那就没必要往数据库里面填充了
                    if (skuReductionTo.getDiscount().compareTo(BigDecimal.ZERO) == 1 || skuReductionTo.getReducePrice().compareTo(BigDecimal.ZERO) == 1) {
                        R r = couponFeignService.saveSkuReduction(skuReductionTo);
                        if (r.getCode() != 0) {
                            log.error("远程保存sku优惠信息失败");
                        }
                    }
                }
            });
        }
    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        LambdaQueryWrapper<SpuInfoEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        String key = (String) params.get("key");
        if (StringUtils.hasLength(key)) {
            lambdaQueryWrapper.and(wapper -> {
                wapper.eq(SpuInfoEntity::getId, key)
                        .or()
                        .like(SpuInfoEntity::getSpuName, key);
            });
        }
        String status = (String) params.get("status");
        if (StringUtils.hasLength(status) && !"0".equalsIgnoreCase(status)) {
            lambdaQueryWrapper.eq(SpuInfoEntity::getPublishStatus, status);
        }
        String catelogId = (String) params.get("catelogId");
        if (StringUtils.hasLength(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            lambdaQueryWrapper.eq(SpuInfoEntity::getCatalogId, catelogId);
        }
        String brandId = (String) params.get("brandId");
        if (StringUtils.hasLength(brandId) && !"0".equalsIgnoreCase(brandId)) {
            lambdaQueryWrapper.eq(SpuInfoEntity::getBrandId, brandId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                lambdaQueryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {

        // 查出当前当前spu对应的所有sku信息
        List<SkuInfoEntity> skus = skuInfoService.getSkuBySpuId(spuId);
        List<Long> skuIds = skus.stream().map(SkuInfoEntity::getSkuId).toList();

        // 查询sku所有可以用来被检索的规格属性 这些属性相同,不用放在stream流中挨个插入操作,时间复杂度变为2N 否则就是N^2
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.baseAttrListForSpuInfo(spuId);
        // 获取所有属性id
        List<Long> attrIds = baseAttrs.stream().map(ProductAttrValueEntity::getAttrId).toList();
        // 根据属性id集合筛选所有属性中得可检索属性
        List<Long> searchAttrs = attrService.selectSearchAttrIds(attrIds);
        Set<Long> search = new HashSet<>(searchAttrs);
        // 筛选出所有规格属性中的可检索属性   这里繁琐的原因是分表之后没有在属性表中直接添加一个是否可检索的冗余字段
        List<SkuEsModel.Attrs> attrsList = baseAttrs.stream().filter(item -> search.contains(item.getAttrId())).map(item -> {
            SkuEsModel.Attrs attrList = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrList);
            return attrList;
        }).toList();

        // hasStock 发送远程调用,库存系统查询是否存在库存,然后再注入
        Result result = wareFeignService.getStock(skuIds);
        Map<Long, Integer> stockMap = null;
        try {
            // 这里创建了一个匿名子类，匿名子类继承TypeReference中的受保护的构造器，创建匿名子类对象时，子类构造器调用父类受保护构造器
            List<SkuStockVo> stockVoList = (List<SkuStockVo>) result.getData();
            System.out.println("stockVoList = " + stockVoList);
            // 远程模块返回的是一个以skuId 和stock 的形式存储的list，这里转为map集合以便取值
            stockMap = stockVoList.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getStock));
        } catch (Exception e) {
            log.error("库存查询返回异常: 原因{}" + e);
        }

        // Lambda表达式可能在另一个线程中执行，如果这个局部变量在外部或者Lambda内部或者同时发生修改，那么可能出现线程安全问题。这里需要重新引用一下
        Map<Long, Integer> finalStockMap = stockMap;
        // 封装每个sku的信息
        List<SkuEsModel> upProducts = skus.stream().map((sku) -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, skuEsModel); // 部分数据存在不一致需要重新注入
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());

            //检查库存
            if (finalStockMap != null && finalStockMap.get(skuEsModel.getSkuId()) != null) {
                skuEsModel.setHasStock(finalStockMap.get(skuEsModel.getSkuId()) > 0);
            } else {
                skuEsModel.setHasStock(false);
            }
            //  TODO 热度评分 hotScore
            skuEsModel.setHotScore(1L);

            //  品牌和分类的名字
            BrandEntity brandEntity = brandService.getById(skuEsModel.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            CategoryEntity categoryEntity = categoryService.getById(skuEsModel.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());

            // 添加可检索字段集合
            skuEsModel.setAttrs(attrsList);
            return skuEsModel;
        }).toList();
        // 将数据发送给es进行保存

        R status = searchFeignService.productStatusUp(upProducts);
        if (status.getCode() == 0) {
            // 远程调用成功 修改当前spu上架状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.statusEnum.SPU_UP.getCode());
        }
        //远程调用失败
        //  重复调用? 接口幂等性,调用失败重试?
        // feign调用流程
        // 1,构造请求数据，将对象转化位json  创建模板，RequestTemplate template = this.buildTemplateFromArgs.create(argv);包含请求方式，请求体，发送对象
        // Retryer retryer = this.retryer.clone();
        // 2,发送请求进行执行  this.executeAndDecode(template, options);
        // 3, 执行请求会有重试机制，while(true) 但是有最大重试限制，默认最多尝试5次


    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity skuInfo = skuInfoService.getById(skuId);
        Long spuId = skuInfo.getSpuId();
        return getById(spuId);
    }


}